<template>
  <div class="admin-contestants">
    <div class="page-header">
      <h2>参赛选手管理</h2>
      
      <div class="search-box">
        <el-input
          placeholder="搜索选手姓名"
          v-model="searchName"
          clearable
          @clear="handleSearch"
          style="width: 200px; margin-right: 10px;">
        </el-input>
        
        <el-select v-model="searchStatus" placeholder="审核状态" clearable @change="handleSearch" style="width: 120px; margin-right: 10px;">
          <el-option label="待审核" :value="0"></el-option>
          <el-option label="已通过" :value="1"></el-option>
          <el-option label="已拒绝" :value="2"></el-option>
        </el-select>
        
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        
        <el-dropdown @command="handleSizeChange" style="margin-left: 10px;">
          <el-button type="text">
            表格密度 <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="medium">默认</el-dropdown-item>
            <el-dropdown-item command="small">紧凑</el-dropdown-item>
            <el-dropdown-item command="mini">迷你</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    
    <el-table
      :data="contestantList"
      border
      :size="tableSize"
      v-loading="loading"
      style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="realName" label="真实姓名" width="100"></el-table-column>
      <el-table-column prop="phone" label="联系电话" width="110">
        <template slot-scope="scope">
          {{ maskPhone(scope.row.phone) }}
        </template>
      </el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="170"></el-table-column>
      <el-table-column prop="contestType" label="参赛类型" width="100">
        <template slot-scope="scope">
          {{ getContestTypeText(scope.row.contestType) }}
        </template>
      </el-table-column>
      <el-table-column prop="workTitle" label="作品集标题" min-width="150">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.workTitle" placement="top" :disabled="scope.row.workTitle.length < 10">
            <span>{{ scope.row.workTitle }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="审核状态" width="90">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="报名时间" width="150">
        <template slot-scope="scope">
          <span class="date-column">{{ formatDateTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-view"
              circle
              @click="viewDetail(scope.row)">
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.status === 0" content="审核通过" placement="top">
            <el-button
              size="mini"
              type="success"
              icon="el-icon-check"
              circle
              @click="handleApprove(scope.row)">
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="scope.row.status === 0" content="审核拒绝" placement="top">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-close"
              circle
              @click="handleReject(scope.row)">
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination" v-if="total > 0">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        @size-change="handlePageSizeChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    
    <!-- 查看详情对话框 -->
    <el-dialog title="参赛选手详情" :visible.sync="detailDialogVisible" width="700px">
      <div v-if="currentContestant">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="真实姓名">{{ currentContestant.realName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ maskIdCard(currentContestant.idCard) }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentContestant.phone }}</el-descriptions-item>
          <el-descriptions-item label="电子邮箱">{{ currentContestant.email }}</el-descriptions-item>
          <el-descriptions-item label="联系地址" :span="2">{{ currentContestant.address }}</el-descriptions-item>
          <el-descriptions-item label="参赛类型">{{ getContestTypeText(currentContestant.contestType) }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusTagType(currentContestant.status)">
              {{ getStatusText(currentContestant.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="作品集标题" :span="2">{{ currentContestant.workTitle }}</el-descriptions-item>
          <el-descriptions-item label="作品集描述" :span="2">
            {{ currentContestant.workDescription || '无' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentContestant.status === 2" label="拒绝原因" :span="2">
            {{ currentContestant.rejectReason || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="报名时间" :span="2">
            {{ formatDateTime(currentContestant.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="action-buttons" v-if="currentContestant.status === 0">
          <el-button type="success" @click="handleApprove(currentContestant)">审核通过</el-button>
          <el-button type="danger" @click="handleReject(currentContestant)">审核拒绝</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 拒绝理由对话框 -->
    <el-dialog title="拒绝理由" :visible.sync="rejectDialogVisible" width="500px">
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝理由" prop="reason">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝理由"
            v-model="rejectForm.reason">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmReject" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminContestants',
  data() {
    return {
      contestantList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchName: '',
      searchStatus: '',
      detailDialogVisible: false,
      rejectDialogVisible: false,
      currentContestant: null,
      rejectForm: {
        id: '',
        reason: ''
      },
      submitting: false,
      tableSize: 'medium'
    }
  },
  created() {
    this.fetchContestants()
  },
  methods: {
    async fetchContestants() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          realName: this.searchName,
          status: this.searchStatus
        }
        console.log('Fetching contestants with params:', params);
        const res = await this.$http.get('/contestants/page', { params })
        console.log('API Response:', res);
        
        if (res.data.code === 1) {
          this.contestantList = res.data.data.records || [];
          this.total = res.data.data.total || 0;
          
          if (this.contestantList.length === 0 && this.currentPage > 1) {
            // If current page is empty but we're not on first page,
            // go back to previous page
            this.currentPage -= 1;
            this.fetchContestants();
            return;
          }
        } else {
          console.error('Error fetching contestants:', res.data.msg);
          this.$message.error(res.data.msg || '获取参赛选手列表失败')
        }
      } catch (error) {
        console.error('获取参赛选手列表失败', error)
        this.$message.error('获取参赛选手列表失败: ' + (error.message || ''))
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchContestants()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchContestants()
    },
    handlePageSizeChange(size) {
      this.pageSize = size
      this.fetchContestants()
    },
    viewDetail(row) {
      this.currentContestant = row
      this.detailDialogVisible = true
    },
    handleApprove(row) {
      this.$confirm(`确定通过"${row.realName}"的参赛申请吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        this.submitting = true
        try {
          const res = await this.$http.put('/contestants/audit', null, {
            params: {
              id: row.id,
              status: 1
            }
          })
          if (res.data.code === 1) {
            this.$message.success('审核通过成功')
            this.fetchContestants()
            if (this.detailDialogVisible) {
              this.detailDialogVisible = false
            }
          } else {
            this.$message.error(res.data.msg || '操作失败')
          }
        } catch (error) {
          console.error('审核失败', error)
          this.$message.error('审核失败')
        } finally {
          this.submitting = false
        }
      }).catch(() => {})
    },
    handleReject(row) {
      this.rejectForm.id = row.id
      this.rejectForm.reason = ''
      this.rejectDialogVisible = true
    },
    async confirmReject() {
      this.submitting = true
      try {
        const res = await this.$http.put('/contestants/audit', null, {
          params: {
            id: this.rejectForm.id,
            status: 2,
            rejectReason: this.rejectForm.reason
          }
        })
        if (res.data.code === 1) {
          this.$message.success('审核拒绝成功')
          this.rejectDialogVisible = false
          this.fetchContestants()
          if (this.detailDialogVisible) {
            this.detailDialogVisible = false
          }
        } else {
          this.$message.error(res.data.msg || '操作失败')
        }
      } catch (error) {
        console.error('审核失败', error)
        this.$message.error('审核失败')
      } finally {
        this.submitting = false
      }
    },
    getContestTypeText(type) {
      const typeMap = {
        1: '手机摄影',
        2: '相机摄影',
        3: '两者都参加'
      }
      return typeMap[type] || '未知'
    },
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      }
      return statusMap[status] || '未知'
    },
    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      }
      return typeMap[status] || 'info'
    },
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    maskIdCard(idCard) {
      if (!idCard) return ''
      return idCard.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3')
    },
    maskPhone(phone) {
      if (!phone) return ''
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
    },
    handleSizeChange(command) {
      this.tableSize = command
    }
  }
}
</script>

<style scoped>
.admin-contestants {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #34495e;
  font-size: 24px;
}

.search-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

/* Table cell styling */
/deep/ .el-table .cell {
  word-break: break-word;
  line-height: 1.5;
  padding-top: 5px;
  padding-bottom: 5px;
}

/deep/ .el-table--mini .cell {
  padding-top: 2px;
  padding-bottom: 2px;
}

/* Fix for dates */
/deep/ .el-table .cell .date-column {
  white-space: nowrap;
}

/* Tooltip for operation buttons */
/deep/ .el-tooltip {
  margin: 0 2px;
}

/* Status tag styles */
/deep/ .el-tag {
  font-size: 12px;
  padding: 0 6px;
  height: 24px;
  line-height: 22px;
}
</style> 